import { reactive } from 'vue'
import { upload } from '@/libs/api/home.js'
/**
 * up-uload组件辅助上传管理
 * @author liruilin
 */
export const useUpUploadTools = function ({ formRef, fileList, change }) {

    // const fileList = reactive({})
    const thatFormRef = formRef
    const thatChange = change

    // 初始图片上传数据
    function mixinUploadInit(data) {
        const uploadKeys = Object.keys(fileList)
        uploadKeys.forEach((prop) => {
            // if ($u.func.isNotNull(data[prop])) {
            if (data[prop]) {
                // thatChange(prop, data[prop])
                const imgs = data[prop]
                fileList[prop] = imgs.map(url => {
                    return {
                        status: 'success',
                        message: '',
                        // size: '',
                        type: "image",
                        thumb: $imgurl(url),
                        url: $imgurl(url)
                    }
                })
            }
        })
    }

    async function mixinAfterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = Array.isArray(event.file) ? [].concat(event.file) : [event.file]
        let fileListLen = fileList[event.name].length - 1
        lists.map((item) => {
            fileList[event.name].push({
                ...item,
                status: 'uploading',
                message: '上传中'
            })
        })

        for (let i = 0; i < lists.length; i++) {
            fileListLen++
            let item = fileList[event.name][fileListLen]
            try {
                const result = await mixinUploadImage(lists[i].url)
                // url  = $imgurl(result.data)
                const url = result.data

                fileList[event.name].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url
                }))

            } catch (e) {
                console.log(e)
                fileList[event.name].splice(fileListLen, 1, Object.assign(item, {
                    status: 'failed',
                    message: '上传失败，请重新选择上传',
                    // url
                }))
            }
        }
        mixinSetFormData(event.name)
    }
    // 删除图片
    function mixinDeletePic(event) {
        fileList[event.name].splice(event.index, 1)
        mixinSetFormData(event.name)
    }
    function mixinSetFormData(name) {
        const formDataVal = fileList[name]
            .filter(e => e.status === 'success')
        thatChange(name, formDataVal)
        // 刷新form表单验证
        thatFormRef.value.validateField(name)
    }
    // 图片上传
    function mixinUploadImage(url) {
        return new Promise((resolve, reject) => {
			upload({
				filePath: url,
				name: 'file',
				// 	getTask: (task, options) => {
				// 	    //  task.onProgressUpdate((res) => {
				// 	    //    console.log('上传进度' + res.progress);
				// 	    //    console.log('已经上传的数据长度' + res.totalBytesSent);
				// 	    //    console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
				// 	    // });
				//     },
			}).then(res => {
				resolve(res.data)
			}).catch(err => {
				console.log(err);
				reject()
			})
        })
    }

    return {
        fileList,
        mixinUploadInit,
        mixinAfterRead,
        mixinDeletePic
    }
}
